﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using Uber.Storage;
using Uber.Messages;
using Uber.HabboHotel.GameClients;
using Uber.HabboHotel.Pathfinding;
using Uber.HabboHotel.Rooms;

namespace Uber.HabboHotel.Items.Interactors
{
    class InteractorGate : FurniInteractor
    {
        int Modes;

        public InteractorGate(int Modes)
        {
            this.Modes = (Modes - 1);

            if (this.Modes < 0)
            {
                this.Modes = 0;
            }
        }

        public override bool OnPlace(GameClient Session, RoomItem Item) { return true; }
        public override void OnRemove(GameClient Session, RoomItem Item) { }

        public override void OnTrigger(GameClient Session, RoomItem Item, int Request, bool UserHasRights)
        {
            if (!UserHasRights)
            {
                return;
            }

            if (this.Modes == 0)
            {
                Item.UpdateState(false, true);
            }

            int currentMode = 0;
            int newMode = 0;

            try
            {
                currentMode = int.Parse(Item.ExtraData);
            }
            catch (Exception) { }

            if (currentMode <= 0)
            {
                newMode = 1;
            }
            else if (currentMode >= Modes)
            {
                newMode = 0;
            }
            else
            {
                newMode = currentMode + 1;
            }

            if (newMode == 0)
            {
                if (Item.GetRoom().SquareHasUsers(Item.X, Item.Y))
                {
                    return;
                }

                var Points = Item.GetRoom().GetAffectedTiles(Item.GetBaseItem().Length, Item.GetBaseItem().Width, Item.X, Item.Y, Item.Rot);

                if (Points == null)
                {
                    Points = new Dictionary<int, Rooms.AffectedTile>();
                }

                foreach (Rooms.AffectedTile Tile in Points.Values)
                {
                    if (Item.GetRoom().SquareHasUsers(Tile.X, Tile.Y))
                    {
                        return;
                    }
                }
            }

            Item.ExtraData = newMode.ToString();
            Item.UpdateState();
            Item.GetRoom().GenerateMaps();
        }
    }
}
